# 129. 求根节点到叶节点数字之和

var sumNumbers = function(root) {
  if (!root) return 0

  return dfs(root, 0)

  function dfs(node, prevNUm) {
    if (node === null) return 0
    const sum = prevNUm * 10 + node.val
    if (node.left === null && node.right === null) {
      return sum
    } else {
      return dfs(node.left, sum) + dfs(node.right, sum)
    }
  }
}
console.log(
  sumNumbers({
    val: 1,
    left: {
      val: 2,
      left: null,
      right: null,
    },
    right: {
      val: 3,
      left: null,
      right: null,
    },
  })
)
console.log(
  sumNumbers({
    val: 0,
    left: {
      val: 1,
      left: null,
      right: null,
    },
    right: null,
  })
)
console.log(
  sumNumbers({
    val: 4,
    left: {
      val: 9,
      left: {
        val: 5,
        left: null,
        right: null,
      },
      right: {
        val: 1,
        left: null,
        right: null,
      },
    },
    right: {
      val: 0,
      left: null,
      right: null,
    },
  })
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
Last Updated: 6/27/2023, 7:40:45 PM